package com.powernode.controller;

import com.powernode.common.Result;
import com.powernode.config.UploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 内容:
 * 作者: cy
 */

@RestController
@RequestMapping("upload")
public class UploadController {
    @Autowired
    private UploadService uploadService;

    /**
     * 上传一个
     */
    @PostMapping("uploadSingleFile")
    public Object uploadFile(MultipartFile mf) {
        try {
            Map<String, Object> data = this.uploadService.uploadFile(mf);
            return new Result(200, "上传成功", data);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(500, "上传失败", e.getMessage());
        }
    }
    /**
     *上传多个
     */
    @PostMapping("uploadMultiFile")
    public Object uploadMultiFile(MultipartFile[] mf){
        List<Map<String,Object>> data=new ArrayList<>();
        if(mf!=null&&mf.length>0){
            for (MultipartFile m : mf) {
                try {
                    Map<String, Object> res = this.uploadService.uploadFile(m);
                    data.add(res);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        if(data.size()>0){
            return new Result(200,"上传成功",data);
        }else{
            return new Result(500,"上传失败");
        }
    }
    /**
     * 删除
     */
    @PostMapping("deleteFile")
    public Result deleteFile(String path){
        try {
            uploadService.deleteFile(path);
            return new Result(200,"删除成功");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(500,"删除失败",e.getMessage());

        }


    }
}

